package com.uetoken.cn.activity;

import android.content.Intent;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.sulink.numberkeyboard.popWindow.BasePayPop;
import com.sulink.numberkeyboard.popWindow.SimplePayPopWindow;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.BaseViewHolder;
import com.uetoken.cn.adapter.ChildPurseAassetAdapter;
import com.uetoken.cn.adapter.GroupedRecyclerViewAdapter;
import com.uetoken.cn.adapter.model.ChildPurseAssetModel;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.MsgBean;
import com.uetoken.cn.bean.SubPursesBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.manager.UEDataManager;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.KeybordUtils;
import com.uetoken.cn.utils.Save2DecimalUtils;
import com.uetoken.cn.view.DialogHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ChildPurseAssetActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.topbar)
    QMUITopBar mTopbar;
    @BindView(R.id.childPurseTv)
    TextView mChildPurseTv;
    @BindView(R.id.childPurseIDTv)
    TextView mChildPurseIDTv;
    @BindView(R.id.balanceTv)
    TextView mBalanceTv;
    @BindView(R.id.freezeTv)
    TextView mFreezeTv;
    @BindView(R.id.childTransferBtn)
    Button mChildTransferBtn;
    @BindView(R.id.mainTransferBtn)
    Button mMainTransferBtn;
    @BindView(R.id.balanceLayout)
    RelativeLayout mBalanceLayout;
    @BindView(R.id.enterAccountEt)
    EditText mEnterAccountEt;
    @BindView(R.id.delIv)
    ImageView mDelIv;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.explainChildTv)
    TextView explainChildTv;

    /**
     * 钱包转账网络请求码
     */
    private static final int NETWORK_REQUEST_PURSE_TRANSFER = 11;
    /**
     * 钱包转账网络请求码
     */
    private static final int INTENT_REQUEST_TRANSFER_CODE = 13;
    private ChildPurseAassetAdapter mChildPurseAassetAdapter;
    private List<ChildPurseAssetModel> mChildPurseAssetModelList;
    private List<SubPursesBean.DataBean> mChildPurseList;
    private SubPursesBean.DataBean mDataBean;
    private SubPursesBean.DataBean titleDataBean = null;
    private int postion;
    private String mianPurseId;
    private String purseName;
    private String childPurseName;
    private String childPurseId;
    private String childTypeId;
    private String childPurseCode;
    private String childBalance;
    private String childFreeze;
    private String transferAmount;
    private String transferName;
    private String tonodecode;
    private String pursepic;
    private String transferPurseName;
    private boolean isTonodecode;
    private boolean isTransferLimitReasonable = false;
    private String pagetransfer;
    private String pagetransfers;
    private String explain;
    private String str1;
    private String str2;
    private int pursetypeid;

    @Override

    public int getLayoutId() {
        return R.layout.activity_child_purse_asset;
    }

    @Override
    public void initView() {
        // 沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            QMUIStatusBarHelper.setStatusBarLightMode(this);
        }
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        mChildPurseList = UEDataManager.getInstance().getChildPurseList();
        Intent intent = getIntent();
        postion = intent.getIntExtra("postion", -1);
        mianPurseId = intent.getStringExtra("purseId");
        purseName = intent.getStringExtra("purseName");
        pagetransfer = intent.getStringExtra("pagetransfer");
        pagetransfers = intent.getStringExtra("pagetransfers");
        pursepic = intent.getStringExtra("pursepic");
        pursetypeid = intent.getIntExtra("pursetypeid", -1);
        mDataBean = mChildPurseList.get(postion);
        mChildPurseList.remove(mDataBean);
        initTopBar();
        childPurseName = mDataBean.getPursename();
        childPurseId = mDataBean.getPurseid() + "";
        childTypeId = mDataBean.getTypeid() + "";
        childPurseCode = mDataBean.getPursecode();
        childBalance = mDataBean.getBalance().toString();
        childFreeze = mDataBean.getFreeze().toString();
        transferPurseName = childPurseName + "(" + childPurseCode + ")";
        mChildPurseTv.setText(childPurseName);
        mChildPurseIDTv.setText(childPurseCode);
        mBalanceTv.setText(Save2DecimalUtils.getDecimalPrecision(mDataBean.getBalance().toString(), 2));
        mFreezeTv.setText(Save2DecimalUtils.getDecimalPrecision(mDataBean.getFreeze().toString(), 2));

        if (mChildPurseList != null) {
            if (mChildPurseList.size() > 0) {
                mChildTransferBtn.setBackgroundResource(R.drawable.blue_circular_bead_shape);
                mChildTransferBtn.setClickable(true);
            } else {
                mChildTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
                mChildTransferBtn.setClickable(false);
            }
        } else {
            mChildTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
            mChildTransferBtn.setClickable(false);
        }
        initTextChangedListener();
        initRecyclerView();
    }

    @Override
    public void init() {

    }

    private void initTopBar() {
        mTopbar.setTitle(purseName + getResources().getString(R.string.tabbar_property_txt));
        mTopbar.addLeftImageButton(R.drawable.ic_back, R.id.qmui_topbar_item_left_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void initTextChangedListener() {
        //InputType.TYPE_NUMBER_FLAG_DECIMAL //小数点型
        //InputType.TYPE_CLASS_NUMBER //整数型
        //设置Input的类型两种都要

        mEnterAccountEt.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);

        //设置字符过滤
        mEnterAccountEt.setFilters(new InputFilter[]{new InputFilter() {

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(".") && dest.toString().length() == 0) {
                    return "0.";
                }
                if (dest.toString().contains(".")) {
                    int index = dest.toString().indexOf(".");
                    int length = dest.toString().substring(index).length();
                    if (length == 3) {
                        return "";
                    }
                }
                return null;
            }
        }});
        isTransferLimitReasonable = checkData();
        if (isTonodecode && isTransferLimitReasonable) {
            mDelIv.setVisibility(View.VISIBLE);
            explainChildTv.setVisibility(View.GONE);
            mChildTransferBtn.setBackgroundResource(R.drawable.blue_circular_bead_shape);
            mChildTransferBtn.setClickable(true);
        } else {
            mDelIv.setVisibility(View.INVISIBLE);
            explainChildTv.setVisibility(View.VISIBLE);
            mChildTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
            mChildTransferBtn.setClickable(false);
        }
        explainChildTv.setText(explain);

        //转账金额输入框
        mEnterAccountEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //输入文本之前的状态
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //输入文字中的状态，count是一次性输入字符数
                isTransferLimitReasonable = checkData();
                if (isTonodecode && isTransferLimitReasonable) {
                    mDelIv.setVisibility(View.VISIBLE);
                    explainChildTv.setVisibility(View.GONE);
                    mChildTransferBtn.setBackgroundResource(R.drawable.blue_circular_bead_shape);
                    mChildTransferBtn.setClickable(true);
                } else {
                    mDelIv.setVisibility(View.INVISIBLE);
                    explainChildTv.setVisibility(View.VISIBLE);
                    mChildTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
                    mChildTransferBtn.setClickable(false);
                }
                explainChildTv.setText(explain);
            }

            @Override
            public void afterTextChanged(Editable s) {
                //输入文字后的状态
                isTransferLimitReasonable = checkData();
                if (isTonodecode && isTransferLimitReasonable) {
                    mDelIv.setVisibility(View.VISIBLE);
                    explainChildTv.setVisibility(View.GONE);
                    mChildTransferBtn.setBackgroundResource(R.drawable.blue_circular_bead_shape);
                    mChildTransferBtn.setClickable(true);
                } else {
                    mDelIv.setVisibility(View.INVISIBLE);
                    explainChildTv.setVisibility(View.VISIBLE);
                    mChildTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
                    mChildTransferBtn.setClickable(false);
                }
                explainChildTv.setText(explain);
            }
        });
    }

    public void initRecyclerView() {
        mChildPurseAssetModelList = new ArrayList<>();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        //初始化适配器
        mChildPurseAassetAdapter = new ChildPurseAassetAdapter(this);
        setChildPurseData(mDataBean, true);
        mChildPurseAassetAdapter.setOnHeaderClickListener(new GroupedRecyclerViewAdapter.OnHeaderClickListener() {
            @Override
            public void onHeaderClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder,
                                      int groupPosition) {
                ChildPurseAassetAdapter mChildPurseAassetAdapter = (ChildPurseAassetAdapter) adapter;
                if (mChildPurseAassetAdapter.isExpand(groupPosition)) {
                    mChildPurseAassetAdapter.collapseGroup(groupPosition);
                } else {
                    mChildPurseAassetAdapter.expandGroup(groupPosition);
                }

                if (KeyboardUtils.isSoftInputVisible(ChildPurseAssetActivity.this)) {
                    KeyboardUtils.hideSoftInput(ChildPurseAssetActivity.this);
                }
            }
        });
        mChildPurseAassetAdapter.setOnChildClickListener(new GroupedRecyclerViewAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder,
                                     int groupPosition, int childPosition) {
                SubPursesBean.DataBean mChildPurseBean = mChildPurseAssetModelList.get(groupPosition).getDataBeanList().get(childPosition);
                setChildPurseData(mChildPurseBean, false);
                if (mChildPurseAassetAdapter.isExpand(groupPosition)) {
                    mChildPurseAassetAdapter.collapseGroup(groupPosition);
                }
            }
        });
        mRecyclerView.setAdapter(mChildPurseAassetAdapter);
    }

    private void setChildPurseData(SubPursesBean.DataBean dataBean, boolean isFirst) {
        mChildPurseAssetModelList.clear();
        ChildPurseAssetModel mChildPurseAssetModel = new ChildPurseAssetModel();

        if (mChildPurseList.size() > 0) {
            if (!isFirst) {
                mChildPurseList.add(titleDataBean);
                titleDataBean = null;
                titleDataBean = dataBean;
            } else {
                titleDataBean = mChildPurseList.get(0);
            }
            mChildPurseList.remove(titleDataBean);
        }
        mChildPurseAssetModel.setDataBean(titleDataBean);
        mChildPurseAssetModel.setDataBeanList(mChildPurseList);
        mChildPurseAssetModelList.add(mChildPurseAssetModel);
        if (mChildPurseAssetModelList.size() > 0) {
            isTonodecode = true;
        } else {
            isTonodecode = false;
        }

        mChildPurseAassetAdapter.setData(mChildPurseAssetModelList);
    }

    private void purseTransfer(String tonodecode, String amount, String paypwd) {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getPurseTansferUrl(), NETWORK_REQUEST_PURSE_TRANSFER,
                Params.getPurseTransferParams(childPurseId, tonodecode, amount, paypwd, pursetypeid, ""));
    }

    private String unit;

    private void reconfirmDialog() {
        boolean isPayPwd = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getBoolean(Constant.IS_PAY_PWD, true);
        if (isPayPwd) {
            //没有支付密码
            new QMUIDialog.MessageDialogBuilder(this)
                    .setTitle(getResources().getString(R.string.str_not_setting_pay_pwd))
                    .setMessage(getResources().getString(R.string.str_you_not_setting_pay_pwd_not_user))
                    .addAction(getResources().getString(R.string.str_later), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    })
                    .addAction(getResources().getString(R.string.str_right_now_setting), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            Intent settingPayPwdIntent = new Intent(ChildPurseAssetActivity.this, ForgetPasswordActivity.class);
                            settingPayPwdIntent.putExtra("pwd", "pay");
                            startActivity(settingPayPwdIntent);

                        }
                    }).show();
        } else {
//        if ("CNV".equals(purseName)) {
//            unit = getResources().getString(R.string.str_unit_yuan);
//        } else if ("USDT".equals(purseName)) {
//            unit = getResources().getString(R.string.str_unit_yuan);
//        } else {
//        }
            unit = purseName;
            tonodecode = titleDataBean.getPursecode();
            transferName = titleDataBean.getPursename() + "(" + tonodecode + ")";
            transferAmount = mEnterAccountEt.getText() + "";
            DialogHelper.showMessageDialog(this, getResources().getString(R.string.str_reconfirm_title_dialog),
                    Html.fromHtml(getResources().getString(R.string.str_reconfirm_msg_dialog, transferAmount + unit,
                            transferName)),
                    getResources().getString(R.string.str_reconfirm_negative_dialog),
                    getResources().getString(R.string.str_reconfirm_positive_dialog), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    }, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            if (Double.parseDouble(transferAmount) <= Double.parseDouble(childBalance)) {

                                SimplePayPopWindow popWindow = new SimplePayPopWindow(ChildPurseAssetActivity.this);
                                transferAmount = String.format("%.2f", Double.parseDouble(transferAmount));
                                popWindow.setTvPayValue(transferAmount + unit);//实际支付金额
//                                popWindow.setTvAmount("200CV");//支付总金额
//                                popWindow.setTvDeduction("抵扣100P币");//优惠金额
                                popWindow.setPayTypeImageUrl(pursepic);
                                popWindow.setTvPayType(purseName);
                                childBalance = String.format("%.2f", Double.parseDouble(childBalance));
                                popWindow.setTvBalance(childBalance);
                                popWindow.showAtLocation(mChildTransferBtn, Gravity.BOTTOM, 0, 0);
                                popWindow.setOnPayListener(new BasePayPop.PayEnterPassWordListener() {
                                    @Override
                                    public void onCancel() {

                                    }

                                    @Override
                                    public void onInputFinished(String passWord) {
                                        //支付密码输入完成
                                        purseTransfer(tonodecode, transferAmount, EncodeUtils.base64Encode2String(passWord.getBytes()));
//                                        Toast.makeText(MainActivity.this,"密码："+passWord,Toast.LENGTH_LONG).show();
                                    }
                                });

//                                Intent pwdIntent = new Intent(ChildPurseAssetActivity.this, PaymentPasswordActivity.class);
//                                pwdIntent.putExtra("amount", transferAmount + unit);
//                                pwdIntent.putExtra("subject", purseName + getResources().getString(R.string.transfer_accounts_txt));
//
//                                //密码输入界面需要显示的参数
//                                pwdIntent.putExtra("pursename", purseName);
//                                pwdIntent.putExtra("icon", pursepic);
//                                pwdIntent.putExtra("balance", childBalance);
//                                startActivityForResult(pwdIntent, INTENT_REQUEST_TRANSFER_CODE);
                            } else {
                                ToastUtils.showShort(getResources().getString(R.string.str_insufficient_balance));
                            }
                        }
                    });
        }
    }

    @OnClick({R.id.balanceLayout, R.id.childTransferBtn, R.id.mainTransferBtn, R.id.delIv})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.balanceLayout:
                intent = new Intent(ChildPurseAssetActivity.this, HistoryActivity.class);
                intent.putExtra("purseId", childPurseId);
                intent.putExtra("historyType", Constant.CHILD_PURSE_HIS);
                intent.putExtra("pursetypeid", pursetypeid);
                startActivity(intent);
                break;
            case R.id.childTransferBtn:
                reconfirmDialog();
                break;
            case R.id.mainTransferBtn:
                intent = new Intent(ChildPurseAssetActivity.this, TransferAccountsActivity.class);
                intent.putExtra("balance", childBalance);
                intent.putExtra("frompurseId", childPurseId);
                intent.putExtra("purseName", purseName);
                intent.putExtra("freeze", childFreeze);
                intent.putExtra("typeid", childTypeId);
                intent.putExtra("pagetransfer", pagetransfer);
                intent.putExtra("pagetransfers", pagetransfers);
                intent.putExtra("transferPurseName", transferPurseName);
                intent.putExtra("isChildPurse", true);
                intent.putExtra("pursepic", pursepic);
                startActivity(intent);
                finish();
                break;
            case R.id.delIv:
                mEnterAccountEt.setText("");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INTENT_REQUEST_TRANSFER_CODE && resultCode == RESULT_OK) {
            String pwd = data.getStringExtra("inputFinish");
            //支付密码输入完成
            purseTransfer(tonodecode, transferAmount, pwd);
        }
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        switch (requestCode) {
            case NETWORK_REQUEST_PURSE_TRANSFER:
                dissmissDialog();
                //{"result":-1,"message":"参数验证错误"}
                MsgBean mMsgBean = new Gson().fromJson(response, MsgBean.class);
                ToastUtils.showShort(mMsgBean.getMessage());
                if (mMsgBean.getResult() > 0) {
                    finish();
                }
                break;

        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
        ToastUtils.showShort(R.string.network_anomaly_please_again);
    }

    public boolean checkData() {
        String fund = mEnterAccountEt.getText() + "";

        if (fund == null || "".equals(fund) || "null".equals(fund)) {
            explain = "";
            str1 = "";
            str2 = "";
            if (fund == null || "".equals(fund) || "null".equals(fund)) {
                str2 = getResources().getString(R.string.str_transfer_in_money_hint);
            }
            explain = !"".equals(str1) && !"".equals(str2) ? "1、" + str1 + ";\n2、" + str2 + ";" : str1 + str2;
            return false;
        } else {
            explain = "";
            str1 = "";
            str2 = "";
            double number = Double.parseDouble(fund);
            if (number < 1) {
                explain = getResources().getString(R.string.str_transfer_in_money_hint);
                return false;
            }
            if (number > Double.parseDouble(childBalance)) {
                explain = getResources().getString(R.string.str_transfer_amount_limit);
                return false;
            }
        }
        return true;
    }
}
